<template>
  <div class="view-file-box" id="view-fiel-page">
    <mobileNavbar :name="titleName" :showBottomBorder="true" @back="handleBack"></mobileNavbar>
    <div class="view-file-body" :class="[formShare && 'share-view-file-body']" v-if="!isPwd" v-loading="fileLoading">
      <dirShare v-if="showType=='directory'" ref="dirShareRef" :docInfo="knowledgeInfo"  @renderFinish="renderFinish" @chagneTitleName="chagneTitleName"
        :formShare="formShare" :docId="docId" :knowledgeInfo="knowledgeInfo" :isEpubUrl="isEpubUrl" :showType='showType' :videoSource="videoSource"></dirShare>
      <viewFileCom :formShare="formShare" :docId="docId" :knowledgeInfo="knowledgeInfo" :tetVal="tetVal" :isEpubUrl="isEpubUrl" :showType='showType' :videoSource="videoSource"  @renderFinish="renderFinish"></viewFileCom>
    </div>
    <div class="view-file-bottom" v-if="!formShare">
      <div class="input-box">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#keowledge-mobile-pinglun"></use>
        </svg>
        <el-input v-model="submitText" :placeholder="$t('message.placeholder.inputCommit')" @keydown.enter="submitPL"></el-input>
      </div>
      <div class="actions-box">
        <svg class="icon" aria-hidden="true" @click="giveLike('LIBRARY')">
          <use v-bind:xlink:href="`#${isLike?'keowledge-mobile-dianzan-xuanzhong':'keowledge-mobile-dianzan'}`"></use>
        </svg>
        <svg class="icon" aria-hidden="true" @click="handleStar" >
          <use v-bind:xlink:href="`#${isStar?'keowledge-mobile-shoucang-xuanzhong':'keowledge-mobile-pinglunshoucang'}`"></use>
        </svg>
      </div>
    </div>
    <div class="password-box" v-if="isPwd">
      <div class="share-pwd-box">
        <div class="share-title-box">
          <img :src="knowledgeInfo.headImg?knowledgeInfo.headImg:userImg">
          <span>{{knowledgeInfo.createBy}}{{$t('message.text.encryPasswordFiles')}}</span>
        </div>
        <div class="share-pwd-input">
          <div class="ple-t">{{$t('message.placeholder.pleasePassword')}}</div>
          <div class="input-box">
            <el-input v-model="pwdInput" @keydown.enter="checkPwd"></el-input>
            <el-button class="button" type="primary" @click="checkPwd">{{$t('message.buttons.submit')}}</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  onMounted,
  getCurrentInstance
} from 'vue' 
import type {ComponentInternalInstance} from 'vue'
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
import { useRoute, useRouter } from "vue-router"
const router = useRouter();
const route = useRoute()
import mobileNavbar from './mobileNavbar.vue';
const BASE_URL = (window.location.protocol + pluginConfig.officeCallBackUrl.substring(pluginConfig.officeCallBackUrl.indexOf('://')+1)) || ''
import { checkShare,getInfo,getStarAll,getLike,getFileUrl,giveGood,docStar,leaveMsg,getSharParams } from "@/api/common";
import { urlParsParams, encryption,isValidUTF8 } from '@/utils/util'
import { enCodeKey } from "@/const/const"
import { getStore,setSessionStore,getSessionStore,delSessionStore } from "@/utils/store.js";
import { Base64 } from "js-base64";
import useUserInfoStore from '@/store/userInfo';
const userStore = useUserInfoStore()
import luckySheetStore from '@/store/luckySheet';
const lsStore = luckySheetStore()
import userImg from '@/assets/common/user.png'
import dirShare from './dirShare.vue'
import viewFileCom from './viewFileCom.vue'
const emit = defineEmits([""])
const props = defineProps({

})

const userIno = ref({})
const titleName =ref('')
const docId = ref('')
const formShare = ref(false)
const docType = ref('')
const submitText = ref('')
const isPwd = ref(false)
const pwdInput = ref('')
const knowledgeInfo = ref(null)
const likeList = ref([])
const isLike = ref(false)
const isStar= ref(false)
const videoSource= ref('')
const showType = ref('')
const tetVal = ref('')
const isEpubUrl =ref(null)
const officeOption =ref({
  url: "",
  isEdit: true,
  id:'',
  mode:'edit',
  fileType: "",
  title: "",
  editUrl:BASE_URL+`/mgr/document/only/office`,// mgr/document
  addUrl:+BASE_URL+`/mgr/document/only/office/add`,
})
const shareKey = ref('')
const shareParams = ref({})
const fileLoading =ref(false)
const dirShareRef = ref()
onMounted(()=>{
  fileLoading.value = true
  userIno.value = getStore({ name: "userInfo" }) || {};
  titleName.value = route.query.fileName
  if(route.query && route.query.type) {
    docType.value = route.query.type
  }
  if(route.query.docId){
    docId.value = route.query.docId
  }
  shareParams.value = route.query
  if(route.params.shareKey){
    formShare.value = true
    shareKey.value = route.params.shareKey
    getShareParams()
  }else if(route.query.security && route.query.key) {
    formShare.value = true
    docId.value = route.query.id || route.query.docId
    checkShareFile()
  }else{
    // 获取文件详细信息
    getDocInfo()
  }
})
function chagneTitleName(val){
  titleName.value = val
}
function getShareParams(){
  getSharParams(shareKey.value).then(res=>{
    if(res.data.code==0){
      shareParams.value = urlParsParams(res.data.data)
      docId.value = shareParams.value.id || shareParams.value.docId
      checkShareFile()
    }
  })
}
function checkShareFile(){
  checkShare({
    key: shareParams.value.key,
  }).then(res => {
    if(res.data.code == 0) {
      if(res.data.data.shareStatus){
        knowledgeInfo.value = res.data.data.dcLibrary
        docType.value = knowledgeInfo.value.type
        titleName.value = knowledgeInfo.value.name
        if(res.data?.data.needPwd){
          isPwd.value = true
          // this.dicData.name = res.data.data.dcLibrary.name
          // this.dicData.headImg = res.data.data.headImg
        }else{
          isPwd.value = false
          getPreviewInfo()
        }
      }else{
        proxy.$mobileMessage({
          text:$t('message.message.shareAddressExpired'),
          type:'error'
        })
      }
      // if(userStore.access_token){
      //   this.getL({ bizType: "LIBRARY", bizResourceId: knowledgeInfo.value.id });
      //   this.getStarAll()
      // }
    }
  })
}
function getDocInfo(){
  getInfo(docId.value).then(res=>{
    if(res.data.code == 0){
      knowledgeInfo.value = res.data.data
      titleName.value = knowledgeInfo.value.name
      getPreviewInfo()
      if(userStore.access_token){
        getL({ bizType: "LIBRARY", bizResourceId: knowledgeInfo.value.id });
        getStarAllFun()
      }
    }
  })
}
function isOffice(val = ''){
  return val.indexOf('office_')!=-1
}
function getPreviewInfo () {
  showType.value = ''
  if(docType.value=='document_upload' || isOffice(docType.value)){
    if(['epub'].indexOf(knowledgeInfo.value.nameSuffix)!=-1){
      showType.value = 'epub'
    }else if(['ofd'].indexOf(knowledgeInfo.value.nameSuffix)!=-1){
      showType.value = 'ofd'
    }else{
      getFileUrl({id:docId.value,isOnlyOffice:true,isTemplate:false}).then(res=>{
        if(res.data.code==0){
          if(['jpg','jpeg','png','gif'].indexOf(knowledgeInfo.value.nameSuffix)!=-1){
              showType.value = 'img'
              videoSource.value = res.data.data.url
          }else if(["avi","wmv","mpg","mpeg","mov","rm","ram","swf","flv","mp4","mp3","wma","avi","rm","rmvb","flv","mpg","mkv"].indexOf(knowledgeInfo.value.nameSuffix)!=-1){
            showType.value = 'video'
            videoSource.value = res.data.data.url
          }else if(['pdf'].indexOf(knowledgeInfo.value.nameSuffix)!=-1){
            let fileUrl = res.data.data.url,fileArr = res.data.data.url.split("//")
            if(fileArr[0]!=window.location.protocol){
              fileArr[0] = window.location.protocol
              fileUrl = fileArr.join("//")
            }
            videoSource.value = fileUrl
            showType.value = 'pdf'
          }else if(['txt'].indexOf(knowledgeInfo.value.nameSuffix)!=-1){
            let xhr = new XMLHttpRequest();
            xhr.open("get", res.data.data.url, true);
            // xhr.responseType = "blob";
            loading.value=true;
            xhr.send();
            xhr.onreadystatechange = function(){
              if(xhr.readyState ===4 && xhr.status === 200){
                if(isValidUTF8(xhr.responseText)){
                  showType.value = 'utf-8'
                }else{
                  showType.value = 'error'
                }
                tetVal.value = xhr.responseText
              }
            }
          }else{
            showType.value='iframe'
            let url = encodeURIComponent(Base64.encode(res.data.data.url))
            videoSource.value = `${pluginConfig.documentUrl}/onlinePreview?url=${url}&officePreviewType=pdf`
          }
          setTimeout(()=>{
            fileLoading.value = false
          },1000*2.5)
        }
      })
    }
  }else{
    if(knowledgeInfo.value.type=="url_address"){
      showType.value = 'iframe'
      videoSource.value = knowledgeInfo.value.urlAddress
      setTimeout(()=>{
        fileLoading.value = false
      },1000*2.5)
    }else{
      showType.value = knowledgeInfo.value.type
    }
  }
}
// 获取文件点赞列表
function getL(query) {
  getLike(query).then((res) => {
    if (res.data.code == 0) {
      likeList.value = res.data.data;
      if (likeList.value.length > 0) {
        for(var i=0;i<likeList.value.length;i++){
          if (likeList.value[i].userId == userIno.value.id) {
            isLike.value = true;
            break;
          } else {
            isLike.value = false;
          }
        }
      } else {
        isLike.value = false;
      }
    }
  });
}
// 获取所有收藏文档集合
function getStarAllFun() {
  getStarAll().then(res => {
    if (res.data && res.data.code == 0) {
      const starList = [...res.data.data] || []
      if(knowledgeInfo.value) {
        isStar.value = starList.indexOf(knowledgeInfo.value.id) > -1
      }
    }
  })
}
function handleStar(){
  if(userStore.access_token) {
    docStar(knowledgeInfo.value.id).then(res => {
      if (res.data && res.data.code == 0) {
        proxy.$mobileMessage({
          text:isStar.value?$t('message.message.unCollectSuccess'):$t('message.message.collectSuccess'),
          type:'success'
        })
        isStar.value = !isStar.value
      }
    })
  }else{
    router.push("/mobile/login")
  }
}
function giveLike(type){
  if(userStore.access_token) {
    giveGood({ bizType: type, bizResourceId: knowledgeInfo.value.id }).then((res) => {
      if (res.data.code == 0) {
        proxy.$mobileMessage({
          text:isLike.value?$t('message.message.startCancel'):$t('message.message.startSuccess'),
          type:'success'
        })
        isLike.value = !isLike.value
      }
    });
  }else{
    router.push("/mobile/login")
  }
}
function submitPL(){
  if(userStore.access_token) {
    let query = {
      knowledgeId: knowledgeInfo.value.id,
      message: submitText.value,
    };
    if(!submitText.value.trim()) return
    leaveMsg(query).then((res) => {
      if (res.data.code == 0) {
        proxy.$mobileMessage({
          text:$t('message.message.commitSuccess'),
          type:'success'
        })
        submitText.value = ''
      }
    });
  }else{
    router.push("/mobile/login")
  }
}
function renderFinish(){
  fileLoading.value = false
}
function handleBack(val){
  if(showType.value=='directory'){
    let enterList = getSessionStore({name:`mobile-${shareKey.value}`}) || []
    if(enterList.length==0){
      router.push(val)
    }else{
      fileLoading.value = true
      const enterId = enterList.pop()
      setSessionStore({name:`mobile-${shareKey.value}`,content:enterList})
      dirShareRef.value.setId()
    }
  }else{
    router.push(val)
  }
}
function checkPwd(){
  let temp = encryption({
    data: {pass: pwdInput.value},
    key: enCodeKey,
    param: ["pass"]
  });
  checkShare({
    key: shareParams.value.key,
    pwd: temp.pass,
  }).then(res => {
    if(res.data.code == 0) {
      if(res.data.data.check) {
        knowledgeInfo.value = res.data.data.dcLibrary
        isPwd.value = false
        getPreviewInfo()
      }else{
        proxy.$onePrompt.$oneNotify({
          type:"error",
          message:$t('message.message.passwordError'),
          title:$t('message.prompt'),
          position:'bottom-right'
        })
      }
    }
  })
}
</script>
<style lang="scss" scoped>
.view-file-box{
  height: 100%;
  width: 100%;
  .view-file-body{
    height: calc(100% - 7.5rem);
    width: 100%;
    position: relative;
    overflow: auto;
    ::v-deep(.iframe){
      height:calc(100% - 0px);
      width:100%;
      border: none;
    }
    ::v-deep(.view-file-mindElixir){
      height:calc(100% - 0px);
    }
    ::v-deep(.topology-view-box){
      height:calc(100% - 0px);
    }
    ::v-deep(.mind-map-page){
      height:calc(100% - 0px);
    }    
  }
  .password-box,.share-view-file-body{
    height: calc(100% - 3.125rem);
  }
  .password-box{
    display: flex;
    align-items: center;
    justify-content: center;
    .share-pwd-box{
      width: calc(100vw - 2.375rem);
      box-shadow: 0rem .25rem 1.25rem 0rem rgba(54,59,76,0.1);
      border-radius: .75rem;
      overflow: hidden;
      .share-title-box{
        display: flex;
        align-items: center;
        padding: 0rem 1.25rem;
        height: 5rem;
        background-image: url('../../assets/images/share-title.png');
        background-size: 100% 100%;
        img{
          width: 2.5rem;
          height: 2.5rem;
          border-radius: .25rem;
          overflow: hidden;
          margin-right: 1rem;
        }
      }
      .share-pwd-input{
        padding: 0rem 1.25rem;
        height: 7.75rem;
        display: flex;
        justify-content: center;
        flex-direction: column;
        .ple-t{
          font-size: .875rem;
          @include SourceHanSansCN-Bold;
          color: #363b4c;
          margin-bottom: .75rem;
        }
        ::v-deep(.input-box){
          display: flex;
          .el-input__wrapper{
            background: #F5F6F7;
            border-radius: .25rem;
            box-shadow: none;
          }
          .is-focus{
            box-shadow: 0 0 0 .0625rem #1E6FFF !important;
          }
          .button{
            margin-left: .75rem;
            width: 5rem;
          }
        }
      }
    }
  }
  .view-file-bottom{
    box-sizing: border-box;
    padding: .625rem .9375rem;
    position: fixed;
    bottom: 0px;
    width: 100%;
    height: 4.375rem;
    border-top: 1px solid #eeeff0;
    display: flex;
    align-items: center;
    .input-box{
      height: 2.75rem;
      border-radius: .375rem;
      background: #f5f6f7;
      display: flex;
      width: 16.8125rem;
      align-items: center;
      .icon{
        margin-left: 1rem;
        width: 1rem;
        height: 1rem;
      }
      ::v-deep(.el-input__wrapper){
        box-shadow: none !important;
        border: none !important;
        background: transparent !important;
        .el-input__inner{
          box-shadow: none !important;
          border: none !important;
          background: transparent !important;
        }
        
      }
    }
    .actions-box{
      margin-left: 1.125rem;
      .icon{
        width: 1.125rem;
        height: 1.125rem;
      }
      .icon+.icon{
        margin-left: 1.25rem;
      }
    }
  }
}
::v-deep(.textareaInput){
  textarea{
    resize: none !important;
    box-shadow: none !important;
  }
}
</style>